home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / poplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  13KB  |  419 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''A POP3 client class.
  5.  
  6. Based on the J. Myers POP3 draft, Jan. 96
  7. '''
  8. import re
  9. import socket
  10. __all__ = [
  11.     'POP3',
  12.     'error_proto']
  13.  
  14. class error_proto(Exception):
  15.     pass
  16.  
  17. POP3_PORT = 110
  18. POP3_SSL_PORT = 995
  19. CR = '\r'
  20. LF = '\n'
  21. CRLF = CR + LF
  22.  
  23. class POP3:
  24.     """This class supports both the minimal and optional command sets.
  25.     Arguments can be strings or integers (where appropriate)
  26.     (e.g.: retr(1) and retr('1') both work equally well.
  27.  
  28.     Minimal Command Set:
  29.             USER name               user(name)
  30.             PASS string             pass_(string)
  31.             STAT                    stat()
  32.             LIST [msg]              list(msg = None)
  33.             RETR msg                retr(msg)
  34.             DELE msg                dele(msg)
  35.             NOOP                    noop()
  36.             RSET                    rset()
  37.             QUIT                    quit()
  38.  
  39.     Optional Commands (some servers support these):
  40.             RPOP name               rpop(name)
  41.             APOP name digest        apop(name, digest)
  42.             TOP msg n               top(msg, n)
  43.             UIDL [msg]              uidl(msg = None)
  44.  
  45.     Raises one exception: 'error_proto'.
  46.  
  47.     Instantiate with:
  48.             POP3(hostname, port=110)
  49.  
  50.     NB:     the POP protocol locks the mailbox from user
  51.             authorization until QUIT, so be sure to get in, suck
  52.             the messages, and quit, each time you access the
  53.             mailbox.
  54.  
  55.             POP is a line-based protocol, which means large mail
  56.             messages consume lots of python cycles reading them
  57.             line-by-line.
  58.  
  59.             If it's available on your mail server, use IMAP4
  60.             instead, it doesn't suffer from the two problems
  61.             above.
  62.     """
  63.     
  64.     def __init__(self, host, port = POP3_PORT, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  65.         self.host = host
  66.         self.port = port
  67.         self.sock = socket.create_connection((host, port), timeout)
  68.         self.file = self.sock.makefile('rb')
  69.         self._debugging = 0
  70.         self.welcome = self._getresp()
  71.  
  72.     
  73.     def _putline(self, line):
  74.         if self._debugging > 1:
  75.             print '*put*', repr(line)
  76.         
  77.         self.sock.sendall('%s%s' % (line, CRLF))
  78.  
  79.     
  80.     def _putcmd(self, line):
  81.         if self._debugging:
  82.             print '*cmd*', repr(line)
  83.         
  84.         self._putline(line)
  85.  
  86.     
  87.     def _getline(self):
  88.         line = self.file.readline()
  89.         if self._debugging > 1:
  90.             print '*get*', repr(line)
  91.         
  92.         if not line:
  93.             raise error_proto('-ERR EOF')
  94.         line
  95.         octets = len(line)
  96.         if line[-2:] == CRLF:
  97.             return (line[:-2], octets)
  98.         if line[0] == CR:
  99.             return (line[1:-1], octets)
  100.         return (line[:-1], octets)
  101.  
  102.     
  103.     def _getresp(self):
  104.         (resp, o) = self._getline()
  105.         if self._debugging > 1:
  106.             print '*resp*', repr(resp)
  107.         
  108.         c = resp[:1]
  109.         if c != '+':
  110.             raise error_proto(resp)
  111.         c != '+'
  112.         return resp
  113.  
  114.     
  115.     def _getlongresp(self):
  116.         resp = self._getresp()
  117.         list = []
  118.         octets = 0
  119.         (line, o) = self._getline()
  120.         while line != '.':
  121.             if line[:2] == '..':
  122.                 o = o - 1
  123.                 line = line[1:]
  124.             
  125.             octets = octets + o
  126.             list.append(line)
  127.             (line, o) = self._getline()
  128.         return (resp, list, octets)
  129.  
  130.     
  131.     def _shortcmd(self, line):
  132.         self._putcmd(line)
  133.         return self._getresp()
  134.  
  135.     
  136.     def _longcmd(self, line):
  137.         self._putcmd(line)
  138.         return self._getlongresp()
  139.  
  140.     
  141.     def getwelcome(self):
  142.         return self.welcome
  143.  
  144.     
  145.     def set_debuglevel(self, level):
  146.         self._debugging = level
  147.  
  148.     
  149.     def user(self, user):
  150.         '''Send user name, return response
  151.  
  152.         (should indicate password required).
  153.         '''
  154.         return self._shortcmd('USER %s' % user)
  155.  
  156.     
  157.     def pass_(self, pswd):
  158.         """Send password, return response
  159.  
  160.         (response includes message count, mailbox size).
  161.  
  162.         NB: mailbox is locked by server from here to 'quit()'
  163.         """
  164.         return self._shortcmd('PASS %s' % pswd)
  165.  
  166.     
  167.     def stat(self):
  168.         '''Get mailbox status.
  169.  
  170.         Result is tuple of 2 ints (message count, mailbox size)
  171.         '''
  172.         retval = self._shortcmd('STAT')
  173.         rets = retval.split()
  174.         if self._debugging:
  175.             print '*stat*', repr(rets)
  176.         
  177.         numMessages = int(rets[1])
  178.         sizeMessages = int(rets[2])
  179.         return (numMessages, sizeMessages)
  180.  
  181.     
  182.     def list(self, which = None):
  183.         '''Request listing, return result.
  184.  
  185.         Result without a message number argument is in form
  186.         [\'response\', [\'mesg_num octets\', ...], octets].
  187.  
  188.         Result when a message number argument is given is a
  189.         single response: the "scan listing" for that message.
  190.         '''
  191.         if which is not None:
  192.             return self._shortcmd('LIST %s' % which)
  193.         return self._longcmd('LIST')
  194.  
  195.     
  196.     def retr(self, which):
  197.         """Retrieve whole message number 'which'.
  198.  
  199.         Result is in form ['response', ['line', ...], octets].
  200.         """
  201.         return self._longcmd('RETR %s' % which)
  202.  
  203.     
  204.     def dele(self, which):
  205.         """Delete message number 'which'.
  206.  
  207.         Result is 'response'.
  208.         """
  209.         return self._shortcmd('DELE %s' % which)
  210.  
  211.     
  212.     def noop(self):
  213.         '''Does nothing.
  214.  
  215.         One supposes the response indicates the server is alive.
  216.         '''
  217.         return self._shortcmd('NOOP')
  218.  
  219.     
  220.     def rset(self):
  221.         '''Unmark all messages marked for deletion.'''
  222.         return self._shortcmd('RSET')
  223.  
  224.     
  225.     def quit(self):
  226.         '''Signoff: commit changes on server, unlock mailbox, close connection.'''
  227.         
  228.         try:
  229.             resp = self._shortcmd('QUIT')
  230.         except error_proto:
  231.             val = None
  232.             resp = val
  233.  
  234.         self.file.close()
  235.         self.sock.close()
  236.         del self.file
  237.         del self.sock
  238.         return resp
  239.  
  240.     
  241.     def rpop(self, user):
  242.         '''Not sure what this does.'''
  243.         return self._shortcmd('RPOP %s' % user)
  244.  
  245.     timestamp = re.compile('\\+OK.*(<[^>]+>)')
  246.     
  247.     def apop(self, user, secret):
  248.         """Authorisation
  249.  
  250.         - only possible if server has supplied a timestamp in initial greeting.
  251.  
  252.         Args:
  253.                 user    - mailbox user;
  254.                 secret  - secret shared between client and server.
  255.  
  256.         NB: mailbox is locked by server from here to 'quit()'
  257.         """
  258.         m = self.timestamp.match(self.welcome)
  259.         if not m:
  260.             raise error_proto('-ERR APOP not supported by server')
  261.         m
  262.         import hashlib as hashlib
  263.         digest = hashlib.md5(m.group(1) + secret).digest()
  264.         digest = ''.join(map((lambda x: '%02x' % ord(x)), digest))
  265.         return self._shortcmd('APOP %s %s' % (user, digest))
  266.  
  267.     
  268.     def top(self, which, howmuch):
  269.         """Retrieve message header of message number 'which'
  270.         and first 'howmuch' lines of message body.
  271.  
  272.         Result is in form ['response', ['line', ...], octets].
  273.         """
  274.         return self._longcmd('TOP %s %s' % (which, howmuch))
  275.  
  276.     
  277.     def uidl(self, which = None):
  278.         """Return message digest (unique id) list.
  279.  
  280.         If 'which', result contains unique id for that message
  281.         in the form 'response mesgnum uid', otherwise result is
  282.         the list ['response', ['mesgnum uid', ...], octets]
  283.         """
  284.         if which is not None:
  285.             return self._shortcmd('UIDL %s' % which)
  286.         return self._longcmd('UIDL')
  287.  
  288.  
  289.  
  290. try:
  291.     import ssl
  292. except ImportError:
  293.     pass
  294.  
  295.  
  296. class POP3_SSL(POP3):
  297.     '''POP3 client class over SSL connection
  298.  
  299.         Instantiate with: POP3_SSL(hostname, port=995, keyfile=None, certfile=None)
  300.  
  301.                hostname - the hostname of the pop3 over ssl server
  302.                port - port number
  303.                keyfile - PEM formatted file that countains your private key
  304.                certfile - PEM formatted certificate chain file
  305.  
  306.             See the methods of the parent class POP3 for more documentation.
  307.         '''
  308.     
  309.     def __init__(self, host, port = POP3_SSL_PORT, keyfile = None, certfile = None):
  310.         self.host = host
  311.         self.port = port
  312.         self.keyfile = keyfile
  313.         self.certfile = certfile
  314.         self.buffer = ''
  315.         msg = 'getaddrinfo returns an empty list'
  316.         self.sock = None
  317.         for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
  318.             (af, socktype, proto, canonname, sa) = res
  319.             
  320.             try:
  321.                 self.sock = socket.socket(af, socktype, proto)
  322.                 self.sock.connect(sa)
  323.             except socket.error:
  324.                 msg = None
  325.                 if self.sock:
  326.                     self.sock.close()
  327.                 
  328.                 self.sock = None
  329.                 continue
  330.  
  331.             break
  332.         
  333.         if not self.sock:
  334.             raise socket.error, msg
  335.         self.sock
  336.         self.file = self.sock.makefile('rb')
  337.         self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  338.         self._debugging = 0
  339.         self.welcome = self._getresp()
  340.  
  341.     
  342.     def _fillBuffer(self):
  343.         localbuf = self.sslobj.read()
  344.         if len(localbuf) == 0:
  345.             raise error_proto('-ERR EOF')
  346.         len(localbuf) == 0
  347.         self.buffer += localbuf
  348.  
  349.     
  350.     def _getline(self):
  351.         line = ''
  352.         renewline = re.compile('.*?\\n')
  353.         match = renewline.match(self.buffer)
  354.         while not match:
  355.             self._fillBuffer()
  356.             match = renewline.match(self.buffer)
  357.         line = match.group(0)
  358.         self.buffer = renewline.sub('', self.buffer, 1)
  359.         if self._debugging > 1:
  360.             print '*get*', repr(line)
  361.         
  362.         octets = len(line)
  363.         if line[-2:] == CRLF:
  364.             return (line[:-2], octets)
  365.         if line[0] == CR:
  366.             return (line[1:-1], octets)
  367.         return (line[:-1], octets)
  368.  
  369.     
  370.     def _putline(self, line):
  371.         if self._debugging > 1:
  372.             print '*put*', repr(line)
  373.         
  374.         line += CRLF
  375.         bytes = len(line)
  376.         while bytes > 0:
  377.             sent = self.sslobj.write(line)
  378.             if sent == bytes:
  379.                 break
  380.             
  381.             line = line[sent:]
  382.             bytes = bytes - sent
  383.  
  384.     
  385.     def quit(self):
  386.         '''Signoff: commit changes on server, unlock mailbox, close connection.'''
  387.         
  388.         try:
  389.             resp = self._shortcmd('QUIT')
  390.         except error_proto:
  391.             val = None
  392.             resp = val
  393.  
  394.         self.sock.close()
  395.         del self.sslobj
  396.         del self.sock
  397.         return resp
  398.  
  399.  
  400. __all__.append('POP3_SSL')
  401. if __name__ == '__main__':
  402.     import sys
  403.     a = POP3(sys.argv[1])
  404.     print a.getwelcome()
  405.     a.user(sys.argv[2])
  406.     a.pass_(sys.argv[3])
  407.     a.list()
  408.     (numMsgs, totalSize) = a.stat()
  409.     for i in range(1, numMsgs + 1):
  410.         (header, msg, octets) = a.retr(i)
  411.         print 'Message %d:' % i
  412.         for line in msg:
  413.             print '   ' + line
  414.         
  415.         print '-----------------------'
  416.     
  417.     a.quit()
  418.  
  419.